package com.weavernorth.test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.weavernorth.modelInterFace.pojo.filedEntity;
import com.weavernorth.util.SendEmail.ExchangeClient;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import static com.weavernorth.util.HttpUtil.*;
import static com.weavernorth.util.dateUtils.*;
import static java.util.stream.Collectors.groupingBy;

/**
 * @Author: BruseeWang
 * @Date: 2020/11/11 16:38
 * @Description: 用于正式系统测试
 */
public class testAction {
    public static void main(String[] args) throws Exception{
        String frUrl="https://finebi.chinaerdos.com:8181/webroot/decision?&requestid=$requestid$";
        if(frUrl.contains("https://finebi.chinaerdos.com:8181/")){
            System.out.println("123");
            frUrl=frUrl.replaceAll("https","http");
        }
        System.out.println(frUrl);
    }
    /***
     * 集合比较
     */
    public static void collection_compare(Integer num){
        //推荐使用HashMap,耗时最少
        Long begin = new Date().getTime();
        HashMap<Integer,String> hashMap=new HashMap<Integer, String>();
        for (int i=1;i<=num;i++){
            hashMap.put(i,"aa");
        }
        Long end = new Date().getTime();
        String str1="HashMap 插入"+num+"条数据,耗时(毫秒)："+(end - begin);
        //JSONObject
        Long begin2 = new Date().getTime();
        JSONObject jsonObject=new JSONObject();
        for (int i=1;i<=num;i++){
            jsonObject.put(""+i+"","aa");
        }
        jsonObject.put("2","456");
        Long end2 = new Date().getTime();
        String str2="JSONObject 插入"+num+"条数据,耗时(毫秒)："+(end2 - begin2);
        //ArrayList by List
        Long begin3 = new Date().getTime();
        List<filedEntity> list=new ArrayList<filedEntity>();
        filedEntity a=new filedEntity();
        for (int i=1;i<=num;i++){
            a.setFiledName(""+i+"");
            a.setFiledValue(""+i+"");
            list.add(a);
        }
        Long end3 = new Date().getTime();
        String str3="ArrayList 插入"+num+"条数据,耗时(毫秒)："+(end3 - begin3);

        //ArrayList to Collection
        Long begin4 = new Date().getTime();
        Collection<filedEntity> coll=new ArrayList<filedEntity>();
        filedEntity entity=new filedEntity();
        for (int i=1;i<=num;i++){
            entity.setFiledName(""+i+"");
            entity.setFiledValue(""+i+"");
            coll.add(entity);
        }
        Long end4 = new Date().getTime();
        String str4="ArrayList to Collection 插入"+num+"条数据,耗时(毫秒)："+(end4 - begin4);
        //LinkedList to List
        Long begin5 = new Date().getTime();
        List<filedEntity> linkedList=new LinkedList<>();
        filedEntity entity2=new filedEntity();
        for (int i=1;i<=num;i++){
            entity2.setFiledName(""+i+"");
            entity2.setFiledValue(""+i+"");
            linkedList.add(entity2);
        }
        Long end5 = new Date().getTime();
        String str5="LinkedList 插入"+num+"条数据,耗时(毫秒)："+(end5 - begin5);

        Long begin6 = new Date().getTime();
        Collection<filedEntity> coll2=new LinkedList<>();
        filedEntity entity3=new filedEntity();
        for (int i=1;i<=num;i++){
            entity3.setFiledName(""+i+"");
            entity3.setFiledValue(""+i+"");
            coll2.add(entity3);
        }
        Long end6 = new Date().getTime();
        String str6="LinkedList to Collection 插入"+num+"条数据,耗时(毫秒)："+(end6 - begin6);
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        System.out.println(str5);
        System.out.println(str6);
    }

    /***
     * 尊享卡接口测试
     */
    public static void api_zxk_Test() throws Exception {
        String request="[{\"djqhm\":\"T1111130\"}]";
        //正式地址
        String url="http://58.18.34.23:18084/FY_TP_SERVICE/FY_BPM_SERVICE.json?method=couponDefer&appId=sapbpm&sign=283ECD6B57768C8C74515D0700B472B5&stype=Q";
        String response=doPost(url,request);
        System.out.println(response);

    }

    /***
     * 付款申请接口测试
     */
    public static void api_fksq_test(){
        String strResponseBody = "";
        String url = "http://121.42.14.180:2000/api-sdk/bpm/payment/check";
        HashMap<String, Object> params = new HashMap<>();
        params.put("sign", "NUNFQ0QyREEzODM4RkRDQTE5OTc1QjhBMEExNTIzRDY0N0RCMzc4Ng==");
        params.put("timestamp", "2021-08-27 15:31:49");
        params.put("appId", "834575");
        params.put("amount", "350.00");
        params.put("payerCompanyCreditNo", "911506937761051841Q");
        params.put("payeeCompanyCreditNo", "911529211174712958");
        try {
            strResponseBody = sendPost(url, "application/x-www-form-urlencoded", params, "key-value");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        JSONObject jsonResult = JSONObject.parseObject(strResponseBody);
        System.out.println(jsonResult.toJSONString());
    }

    /***
     * exchange邮件发送功能
     */
    public static void api_senEmail_test(){
        String emailAddress="17610919982@163.com";
        String emailTitle="邮件测试3";
        String emailContent="邮件内容33";
        String host="webmail.chinaerdos.com";
        String account="bpmmail@chinaerdos.com";
        String pass="Aa111111";
        ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
                .hostname(host)
                .exchangeVersion(ExchangeVersion.Exchange2010)
                .username(account)
                .password(pass)
                .build();
        Boolean result=client.sendExchange(emailAddress,emailTitle,emailContent);
    }


    /**
     * 判断字符串是否可以转化为JSON数组
     * @param content
     * @return
     */
    public static boolean isJsonArray(String content) {
        if(StringUtils.isBlank(content))
            return false;
        StringUtils.isEmpty(content);
        try {
            JSONArray jsonStr = JSONArray.parseArray(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static String sendPost(String strUrl, String contentType, Map<String, Object> params, String sType) throws IOException {
        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(strUrl);
        //请求参数：key-value
        if (!"json".equals(sType)) {
            List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                BasicNameValuePair pair = new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString());
                pairList.add(pair);
            }
            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));
        } else {
            //装填参数：json
            JSONObject object = new JSONObject();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                object.put(entry.getKey().toString(), entry.getValue().toString());
            }
            StringEntity stringEntity = new StringEntity(object.toString(), "utf-8");
            httpPost.setEntity(stringEntity);
        }
        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        //"application/json"
        httpPost.setHeader("Content-type", contentType);
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "*/*");

        try {
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
//          log.info("返回状态=="+response);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strBody;
    }
    /**
     * 获取FTPClient对象
     *
     * @param ftpHost
     *            FTP主机服务器
     * @param ftpPassword
     *            FTP 登录密码
     * @param ftpUserName
     *            FTP登录用户名
     * @param ftpPort
     *            FTP端口 默认为21
     * @return
     */
    public static Channel getFTPClient(String ftpHost, String ftpUserName,
                                         String ftpPassword, int ftpPort) {
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(ftpUserName,ftpHost,ftpPort);
            sshSession = jsch.getSession(ftpUserName, ftpHost, ftpPort);
            sshSession.setPassword(ftpPassword);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            System.out.println("Session 连接成功。");
            channel = sshSession.openChannel("sftp");
            channel.connect();
            System.out.println("Channel  连接成功。");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接失败"+e.toString());
        }finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }
        return channel;
    }
    private static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    private static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    public static String sendPost(String strUrl, String strRequestXml, String strEncoding,String strUsername,String strPassword) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);
            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            System.out.println("请求地址=" + strUrl);

            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                System.out.println("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            System.out.println("异常捕获=" + e);
        }
        return strBody;
    }

}

